<template>
  <el-card style="max-width: 100%">
    <template #header>
      <div class="card-header">
        <span>消息列表</span>
        <el-button type="primary" @click="handleAdd">添加消息</el-button>
      </div>
    </template>
    <!-- 消息列表表格 -->
    <el-table :data="messageData.slice((currentPage-1)*pageSize,pageSize*currentPage)" border stripe style="width: 100%">
      <el-table-column label="编号" width="80">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" width="180"></el-table-column>
      <el-table-column prop="type" label="类型" width="120"></el-table-column>
      <el-table-column label="状态" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.read ? '' : 'danger'">
            {{ scope.row.read ? '已读' : '未读' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="time" label="发布时间" width="180"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next"
      :total="messageData.length"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
    />
  </el-card>

  <!-- 消息编辑/添加对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="isEdit ? '编辑消息' : '添加消息'"
    width="500"
  >
    <el-form :model="messageForm">
      <el-form-item label="标题" :label-width="formLabelWidth">
        <el-input v-model="messageForm.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="类型" :label-width="formLabelWidth">
        <el-select v-model="messageForm.type" placeholder="请选择">
          <el-option label="系统通知" value="system"></el-option>
          <el-option label="天气预警" value="weather"></el-option>
          <el-option label="农事提醒" value="reminder"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容" :label-width="formLabelWidth">
        <el-input v-model="messageForm.content" type="textarea" />
      </el-form-item>
      <el-form-item label="详细内容" :label-width="formLabelWidth">
        <el-input v-model="messageForm.detail" type="textarea" :rows="4" />
      </el-form-item>
      <el-form-item label="状态" :label-width="formLabelWidth">
        <el-switch v-model="messageForm.read" active-text="已读" inactive-text="未读" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";

// 分页相关
const currentPage = ref(1);
const pageSize = ref(5);

// 数据相关
const messageData = ref([]);
const dialogFormVisible = ref(false);
const isEdit = ref(false);
const formLabelWidth = '80px';

// 表单数据
const messageForm = ref({
  id: '',
  title: '',
  type: '',
  content: '',
  detail: '',
  read: false,
  time: ''
});

// 获取消息列表
const getMessageData = () => {
  fetch("http://localhost:3000/messages")
    .then(res => res.json())
    .then(data => {
      messageData.value = data;
    });
};

// 添加消息
const handleAdd = () => {
  isEdit.value = false;
  messageForm.value = {
    id: '',
    title: '',
    type: '',
    content: '',
    detail: '',
    read: false,
    time: new Date().toISOString()
  };
  dialogFormVisible.value = true;
};

// 编辑消息
const handleEdit = (row) => {
  isEdit.value = true;
  messageForm.value = { ...row };
  dialogFormVisible.value = true;
};

// 提交表单
const submitForm = () => {
  if (isEdit.value) {
    // 编辑
    fetch(`http://localhost:3000/messages/${messageForm.value.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(messageForm.value)
    })
    .then(() => {
      ElMessage.success('编辑成功');
      dialogFormVisible.value = false;
      getMessageData();
    });
  } else {
    // 添加
    messageForm.value.time = new Date().toISOString();
    fetch("http://localhost:3000/messages", {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(messageForm.value)
    })
    .then(() => {
      ElMessage.success('添加成功');
      dialogFormVisible.value = false;
      getMessageData();
    });
  }
};

// 删除消息
const handleDelete = (id) => {
  fetch(`http://localhost:3000/messages/${id}`, {
    method: 'DELETE'
  })
  .then(() => {
    ElMessage.success('删除成功');
    getMessageData();
  });
};

onMounted(() => {
  getMessageData();
});
</script>

<style>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>